package server;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PerformanceMeasure extends Thread {
	private Logger logger;
	private Runtime rt;
	private Sigar sigar;
	private CpuInfo[] cpuinfo;
	private ProcCpu cpu;
	private boolean running;

	public static final int MEASURE_INTERVAL = 1000;

	public PerformanceMeasure() {
		logger = LoggerFactory.getLogger(PerformanceMeasure.class);
		rt = Runtime.getRuntime();
		sigar = new Sigar();
		cpuinfo = null;
		try {
			cpuinfo = sigar.getCpuInfoList();
		}
		catch (SigarException se) {
			se.printStackTrace();
		}
		logger.info("Total number of CPUs {}", cpuinfo.length);
		running = true;
	}

	public void run() {
		Statistics stats = Statistics.getInstance();
		while (running) {
			long id = sigar.getPid();

			cpu = null;
			try {
				cpu = sigar.getProcCpu(id);
				logger.info("CPU usage {}", cpu.getPercent());
			}
			catch (SigarException e1) {
				e1.printStackTrace();
			}
			logger.info("Total free memory {}", rt.freeMemory());
			
			logger.info(stats.generateStatistics());

			try {
				sleep(MEASURE_INTERVAL);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public synchronized void close() {
		running = false;
	}
}
